package be.kuleuven.mume.paginas;

import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
import be.kuleuven.mume.R;
import be.kuleuven.mume.arrayAdapters.UpdatesArrayAdapter;
import be.kuleuven.mume.framework.Update;
import be.kuleuven.mume.hulpklassen.DataFetcher;
import be.kuleuven.mume.hulpklassen.RetainListActivity;
import be.kuleuven.mume.hulpklassen.JSONParser.UpdatesParser;
import be.kuleuven.mume.listProxys.DeviderProxy;
import be.kuleuven.mume.listProxys.LastCellLoadingProxy;

public class UpdatesPagina extends RetainListActivity<Update> implements OnItemClickListener{
	
	private List<Update> updates;
	private ArrayAdapter<Update> updatesAdapter;
	private LastCellLoadingProxy loadingProxy;
	private DataFetcher<Update> datafetcher;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updates_pagina);

		ListView table = (ListView)findViewById(R.id.updatesList);
		
		updates = getItems();
		updatesAdapter = new UpdatesArrayAdapter(this, updates);
		DeviderProxy deviderAdapter = new DeviderProxy(this, updatesAdapter);
		UpdatesParser parser = new UpdatesParser();
	    datafetcher = new DataFetcher<Update>(parser, Update.URL, table, updates, this.getBaseContext()){
	    	public void DataReceived(){
				if(!datafetcher.hasMoreData()){
					loadingProxy.setIsLoading(false);
				}
				updatesAdapter.notifyDataSetChanged();
	    	}
	    };
	    
	    loadingProxy = new LastCellLoadingProxy(deviderAdapter);
	    loadingProxy.noDataString_ID = R.string.geen_updates;
	    
		table.setAdapter(loadingProxy);
		
		table.setOnItemClickListener(this);
	}
	
	public void onItemClick(AdapterView<?> parent, 
			View v, int position, long id ) {
		Update u = updatesAdapter.getItem(position);
		if(u == null)
			return;
		
		Intent i = new Intent(Intent.ACTION_VIEW);  
		i.setData(Uri.parse(u.getLink()));  
		startActivity(i); 
	}
}
